package cn.lg.soar.boot.fc.service.impl;

import cn.lg.soar.boot.fc.entity.RoomFurniture;
import cn.lg.soar.boot.fc.entity.importExcel.FurnitureIo;
import cn.lg.soar.boot.fc.entity.vo.FurnitureExExcelVo;
import cn.lg.soar.boot.fc.service.RoomFurnitureService;
import cn.lg.soar.common.data.msg.I18n;
import cn.lg.soar.common.model.HttpResult;
import cn.lg.soar.common.model.IPageQuery;
import cn.lg.soar.common.model.PageQuery;
import cn.lg.soar.common.model.PageResult;
import cn.lg.soar.common.util.AssertUtil;
import cn.lg.soar.common.util.BeanCopier;
import cn.lg.soar.common.util.ParameterUtil;
import cn.lg.soar.core.util.easyexcel.ExcelUtil;
import cn.lg.soar.database.query.QueryParams;
import cn.lg.soar.database.query.SqueryWapper;
import cn.lg.soar.database.util.PageUtils;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.lg.soar.database.base.service.impl.BaseServiceImpl;
import cn.lg.soar.boot.fc.mapper.FurnitureMapper;
import cn.lg.soar.boot.fc.entity.Furniture;
import cn.lg.soar.boot.fc.service.FurnitureService;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 配套表
 * @author BoBo
 * @since 2025-01-15
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@Service
public class FurnitureServiceImpl extends BaseServiceImpl<FurnitureMapper, Furniture> implements FurnitureService {

    @Autowired
    private RoomFurnitureService roomFurnitureService;

    private SqueryWapper<Furniture> furnitureWapper;

    private SqueryWapper<RoomFurniture> roomFurnitureWapper;

    @Override
    public HttpResult<Serializable> addFurniture(Furniture furniture) {
        ParameterUtil.notNull(furniture, "数据不能为空");
        //获取图片附件url集合
        List<String> imgList = furniture.getImgList();
        StringBuffer img = new StringBuffer();
        //
        if (imgList!=null &&!CollectionUtils.isEmpty(imgList)) {
            //处理url集合数据，存入数据库
            for (int i = 0; i < imgList.size(); i++) {
                if (i > 0) {
                    img.append(",");
                }
                img.append(imgList.get(i));
            }
        }
        furniture.setImg(img.toString());

        //已使用数量是总数减去未使用数量
        //添加时，未使用数量和总数量保持一致
        furniture.setFuremain(furniture.getFutotla());

        AssertUtil.isTrue(save(furniture), "创建失败");
        return HttpResult.success("创建成功");
    }

    @Override
    public HttpResult<Serializable> updateFurniture(Furniture furniture) {
        ParameterUtil.notNull(furniture, "数据不能为空");
        //获取图片附件url集合
        List<String> imgList = furniture.getImgList();
        StringBuffer img = new StringBuffer();
        //
        if (imgList!=null &&!CollectionUtils.isEmpty(imgList)) {
            //处理url集合数据，存入数据库
            for (int i = 0; i < imgList.size(); i++) {
                if (i > 0) {
                    img.append(",");
                }
                img.append(imgList.get(i));
            }
        }
        furniture.setImg(img.toString());

        //已使用数量不变
        //未使用数量为总数减去使用数量
        furniture.setFuremain(furniture.getFutotla()-furniture.getFuinuse());

        AssertUtil.isTrue(super.updateById(furniture), "更新失败");
        //return ;
        return HttpResult.success("更新成功");
    }

    @Override
    public HttpResult<Furniture> detail(Long id) {
        ParameterUtil.notNull(id, "缺少数据id");
        Furniture data = super.getById(id);
        ParameterUtil.notNull(data, "数据不存在", id);

        String img = data.getImg();
        //判断当img只有不为空的时候做处理
        if (img!=null && !img.isEmpty()) {
            List<String> imgList = new ArrayList<>();
            String[] strArray = img.split(",");
            for (String s : strArray) {
                imgList.add(s);
            }
            data.setImgList(imgList);
        }
        return HttpResult.data(data);
    }

    @Override
    public HttpResult<PageResult<Furniture>> getFind(PageQuery pageQuery, QueryParams params, Long roomFurnitureid) {
        if (roomFurnitureWapper == null) {
            roomFurnitureWapper = new SqueryWapper<>(RoomFurniture.class);
        }
        QueryWrapper<RoomFurniture> roomFurnitureWrapper = Wrappers.query();
        //查询字段r
        List<String> roomFurnitureS = new ArrayList<>();
        roomFurnitureS.add("furnitureid");//只查询配套id
        //查询where
        List<String> roomFurnitureF = new ArrayList<>();
        roomFurnitureF.add("roomid-eq~"+roomFurnitureid);
        //roomFurnitureWapper.setSelect(roomFurnitureS,roomFurnitureWrapper);
        roomFurnitureWapper.setWhere(roomFurnitureF,roomFurnitureWrapper);

        //super.list(roomFurnitureWrapper);
        List<RoomFurniture> rflist = roomFurnitureService.list(roomFurnitureWrapper);
        //查询条件
        List<String> flist = new ArrayList<>();
        if (!rflist.isEmpty()) {
            StringBuffer stringBuffer = new StringBuffer("id-notIn~");
            for (int i = 0; i < rflist.size(); i++) {
                RoomFurniture roomFurniture = rflist.get(i);
                if (i>0) {
                    stringBuffer.append("~");
                }
                //塞入配套id
                stringBuffer.append(roomFurniture.getFurnitureid());
            }
            flist.add(stringBuffer.toString());
        }
        //查询配套表
//        if (params == null) {
//            params = new QueryParams();
//        }
        if (furnitureWapper == null) {
            furnitureWapper = new SqueryWapper<>(Furniture.class);
        }
        QueryWrapper<Furniture> furnitureWrapper = Wrappers.query();

        PageResult<Furniture> result = new PageResult<>();
        if (pageQuery == null || pageQuery.getPageSize() <= 0) {
            // 不分页
            //替换查询条件为flist
            furnitureWapper.setWhere(flist, furnitureWrapper);
            furnitureWapper.setSelect(params.getFields(), furnitureWrapper);
            furnitureWapper.setOrderBy(params.getOrderBy(), furnitureWrapper);
            List<Furniture> list = super.list(furnitureWrapper);
            result.setList(list);
            return HttpResult.data(result);
        }
        result.setPageNo(pageQuery.getPageNo());
        result.setPageSize(pageQuery.getPageSize());
        result.setQueryType(pageQuery.getQueryType());

        if (IPageQuery.QueryType.total.equals(pageQuery.getQueryType())) {
            // 查总记录数
            //替换查询条件
            furnitureWapper.setWhere(flist, furnitureWrapper);
            result.setTotal(super.count(furnitureWrapper));
            return HttpResult.data(result);
        }
        // 分页查数据
        IPage<Furniture> page = PageUtils.toPage(pageQuery);

        furnitureWapper.setWhere(flist, furnitureWrapper);
        furnitureWapper.setSelect(params.getFields(), furnitureWrapper);
        furnitureWapper.setOrderBy(params.getOrderBy(), furnitureWrapper);

        page = super.page(page, furnitureWrapper);
        result.setTotal(page.getTotal());
        result.setList(page.getRecords());

        return HttpResult.data(result);
    }

    @Override
    public HttpResult<Serializable> updateSort(List<Map<String, BigInteger>> sortedData) {
        if (null == sortedData || 0 >= sortedData.size()) {
            return HttpResult.fail("4000", "排序数据不可为空", "error");
        }

        sortedData.forEach(item->{
            Long id = item.get("id").longValue();
            int orders = item.get("orders").intValue();
            if (!item.containsKey("id") || !item.containsKey("orders")) {
                return;
            }
            Furniture furniture = new Furniture();
            furniture.setId(id);
            furniture.setOrders(orders);
            //执行修改
            super.updateById(furniture);
        });
        return HttpResult.success("排序成功");
    }

    @Override
    public void exports(List<Furniture> list, HttpServletResponse resp) {
        List<FurnitureExExcelVo> listVo = new ArrayList<>();

        //当list为空时，下载导入模板
       if (CollectionUtils.isEmpty(list)) {
           ExcelUtil.exportExcelHead("配套", listVo, FurnitureIo.class, resp);
       }
        //当list不为空时，导出数据
       if (!CollectionUtils.isEmpty(list)) {
           for (Furniture record : list) {
               FurnitureExExcelVo vo = new FurnitureExExcelVo();
               BeanUtils.copyProperties(record, vo);

               String ptstata = "其他";
               if(record.getState() == 1){
                   ptstata = "未配置";
               }else if(record.getState() == 2){
                   ptstata = "已配置";
               }else if(record.getState() == 3){
                   ptstata = "使用中";
               }
               vo.setState(ptstata);

               listVo.add(vo);
           }
           // 导出
           ExcelUtil.exportExcelHead("配套", listVo, FurnitureExExcelVo.class, resp);
       }
    }

    @Override
    public HttpResult<Void> imports(MultipartFile files) {
        List<FurnitureIo> dataList;
        try {
            dataList = EasyExcel.read(files.getInputStream()).head(FurnitureIo.class)
                    .sheet()
                    .doReadSync();
        } catch (IOException e) {
            return HttpResult.fail("B0000", I18n.build("数据格式存在问题，无法读取！"));
        }
        if (CollectionUtils.isEmpty(dataList)) {
            return HttpResult.fail("B0000", I18n.build("数据为空！"));
        }

        for (FurnitureIo data : dataList) {
            Furniture furniture = new Furniture();
            BeanUtils.copyProperties(data, furniture);

            int ptstat= 4;
            if (data.getState() !=null) {
                if (data.getState().equals("未配置")) {
                    ptstat=1;
                } else if (data.getState().equals("已配置")) {
                    ptstat=2;
                } else if (data.getState().equals("使用中")) {
                    ptstat=3;
                }
            }
            furniture.setState(ptstat);
            //总配套数量为剩余配套数量，一配套数量置为0
            furniture.setFuinuse(0);
            furniture.setFuremain(furniture.getFutotla());

            AssertUtil.isTrue(super.save(furniture), "新增失败");
        }

        return HttpResult.success();
    }

}
